package com.herohoy.games.scanmines;

import java.security.SecureRandom;

public class ScanmineCore {
    /**
     * 格子平台初始化并返回
     * @param height 高度
     * @param width 宽度
     * @return 平台数组
     */
    public int[][] getInitPlatform(int height, int width) {
        if(height < 10) {
            height = 10;
        }
        if(width < 10) {
            width = 10;
        }
        if(height > 32) {
            height = 32;
        }
        if(width > 20) {
            width = 20;
        }

        return new int[height][width];
    }

    /**
     * 初始化雷区
     * @param minesNum 地雷数量
     * @param platform 格子平台数组
     */
    public void initMines(int minesNum, int[][] platform) {
        if(platform.length < 10 || platform.length > 32) {
            return;
        }
        if(minesNum < 20) {
            minesNum = 20;
        }
        int total = platform.length * platform[0].length;
        if(minesNum > total / 2) {
            minesNum = total / 2;
        }
        SecureRandom random = new SecureRandom();
        int originNum = minesNum;
        int temp;
        for(int i = 0; i < platform.length; i++) {
            int[] row = platform[i];
            for (int j = 0; j < row.length; j++) {
                total--;
                if(minesNum == 0) {
                    break;
                }
                temp = random.nextInt(99) + 1;
                if(temp <= originNum || total - minesNum == 0) {
                    platform[i][j] = -1;
                    minesNum--;
                }
            }
            if(minesNum == 0) {
                break;
            }
        }
    }

    /**
     * 点击当前格子时获取该格子的状态（踩雷或得到周围雷数）
     * @param yindex 纵轴坐标
     * @param xindex 横轴坐标
     * @param platform 格子平台数组
     * @return 当前格子周围包含的雷数，如为-1表示踩雷
     */
    public int getCurrentCell(int yindex, int xindex,
                                int[][] platform) {
        int result1 = platform[yindex][xindex];
        if(result1 == -1) {
            return result1;
        }
        int realxposless = yindex == 0 ? 0 : yindex - 1;
        int realxposmore = yindex > platform.length - 1 ?
                platform.length - 1 : yindex + 1;
        for(int i = realxposless; i <= realxposmore; i++) {
            int realyposless = xindex == 0 ? 0 : xindex - 1;
            int realyposmore = xindex > platform[i].length - 1 ?
                    platform[i].length - 1 : xindex + 1;
            for(int j = realyposless; j <= realyposmore; j++) {
                if(platform[i][j] == -1) {
                    result1++;
                }
            }
        }
        return result1;
    }

}

    